package main.java.com.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import main.java.com.util.ConnDb;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * !!! Anti-fake label !!!
 * ClassName: HomePageAction
 * Package: main.java.com.action
 * Description:
 *
 * @Author 22软件6班 陈彬
 * @Create 2023/12/25 19:55
 * @Version 1.0
 **/
@WebServlet("/HomePageServlet")
public class HomePageAction extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //配置请求和响应的字符集为UTF-8
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //传入的参数表示为数据查询
        String count=request.getParameter("count");
        //创建一个jsonobject对象
        JSONObject jsonObject=new JSONObject();
        if ("1".equals(count)){//count=1传入的参数表示为数据查询
            List<HashMap> list=this.querySexCount();
            jsonObject.put("list",list);
            //将jsonobject转化为字符串
            String json= JSON.toJSONString(jsonObject);
            //将json字符串写入响应信息中
            response.getWriter().write(json);
        }else {
            //将首页页面写入到Session
            request.getSession().setAttribute("menuUrl","homePage.jsp");
            //实现跳转到个人中心修改页面
            //getRequestDispatchar获取转发对象
            request.getRequestDispatcher("/WEB-INF/jsp/shellPage.jsp").forward(request,response);
        }
    }
    //查询男女统计人数
    public  List<HashMap> querySexCount(){
        List<HashMap> list=new ArrayList<>();
        try{
            //调用连接数据库方法
            ConnDb db=new ConnDb();
            Connection conn = db.dataBaseConnectionTest();
            System.out.println("=====开始执行查询sql======");
            //构建SQL命令语句
            String sql="SELECT COUNT(sex) AS VALUE,sex AS name\n" +
                    "FROM tb_student_info GROUP BY sex";
            //利用PreparedStatement预处理接口创建对象pstm
            PreparedStatement pstmt=conn.prepareStatement(sql);
            //执行方法
            ResultSet rs=pstmt.executeQuery();
            while (rs.next()){//如果由查询到数据，则进入while循环
                HashMap map=new HashMap();
                map.put("value",rs.getInt("value"));
                map.put("name",rs.getString("name"));
                list.add(map);
            }
            conn.close();//关闭数据
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
}
